package com.netintech.process.model;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.netintech.common.utils.MessageUtils;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 流程模型控制器类
 * @author admin
 */
@Controller
@RequestMapping("/process/modelerView")
public class ModelEditorJsonController extends BaseController implements ModelDataJsonConstants {

      protected static final Logger LOGGER = LoggerFactory.getLogger(ModelEditorJsonController.class);

      @Autowired
      private RepositoryService repositoryService;

      @Autowired
      private ObjectMapper objectMapper;

        @Value("${rsa.private_key}")
        private String privateKey;

        @GetMapping("/editor/stencilset")
        @ResponseBody
        public Object getStencilset(){
            InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("static/stencilset.json");
            try {
                return IoUtil.read(stencilsetStream, StandardCharsets.UTF_8);
            } catch (Exception e) {
                LOGGER.error("Error while loading stencil set", e);
                throw new ActivitiException("Error while loading stencil set", e);
            }
        }

      @GetMapping(value="/model/{modelId}/json")
      @ResponseBody
      public Object getEditorJson(@PathVariable String modelId) {
        ObjectNode modelNode = null;
        //将id解密
        Model model = repositoryService.getModel(modelId);
        if (model != null) {
          try {
            if (StringUtils.isNotEmpty(model.getMetaInfo())) {
              modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            } else {
              modelNode = objectMapper.createObjectNode();
              modelNode.put(MODEL_NAME, model.getName());
            }
            modelNode.put(MODEL_ID, model.getId());
            ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
                new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
            modelNode.set("model", editorJsonNode);

          } catch (Exception e) {
            LOGGER.error("Error creating model JSON", e);
            throw new ActivitiException("Error creating model JSON", e);
          }
        }
        return modelNode;
      }

    /**
     * 保存模型数据
     * @param modelId
     * @param name
     * @param description
     * @param jsonXml
     * @param svgXml
     */
    @PostMapping("/model/{modelId}/save")
    @ResponseBody
    public RequestResult saveModel(@PathVariable(value = "modelId") String modelId, String name, String description,
                          @RequestParam("json_xml") String jsonXml, @RequestParam("svg_xml") String svgXml) {
        try {
            if(StringUtils.isBlank(jsonXml)){
                throw new ActivitiException(MessageUtils.message("json.xml.is.empty"));
            }
            Model model = repositoryService.getModel(modelId);
            if(model!=null){
                ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                modelJson.put(MODEL_NAME, name);
                modelJson.put(MODEL_DESCRIPTION, description);
                model.setMetaInfo(modelJson.toString());
                model.setName(name);

                repositoryService.saveModel(model);
                repositoryService.addModelEditorSource(model.getId(), jsonXml.getBytes(StandardCharsets.UTF_8));
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                final byte[] result = outStream.toByteArray();
                repositoryService.addModelEditorSourceExtra(model.getId(), result);
                outStream.close();
            }
        } catch (Exception e) {
            LOGGER.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
        return RequestResult.success("请求成功");
    }
}
